package com.css.zfzx.fwsjcj.modules.group.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleUserEntity;
import com.css.bpm.platform.org.user.repository.UserRepository;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.modules.basecontroller.service.FwDivisionService;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupEntity;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupUserEntity;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupQueryRepository;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupRepository;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupUserRepositoty;
import com.css.zfzx.fwsjcj.modules.group.service.FwGroupService;
import com.css.zfzx.fwsjcj.modules.group.service.FwGroupUserService;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupEntityVo;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupUserFormCountVO;
import com.css.zfzx.fwsjcj.modules.group.vo.FwGroupVo;
import com.css.zfzx.fwsjcj.modules.group.vo.GroupVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.service.TaskFromService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@PropertySource(value = "classpath:platform-config.yml")
public class FwGroupServiceImpl implements FwGroupService {
    @Autowired
    FwGroupUserService fwGroupUserService;
    @Autowired
    FwGroupRepository fwGroupRepository;
    @Autowired
    FwGroupQueryRepository fwGroupQueryRepository;
    @Autowired
    FwDivisionService fwDivisionService;
    @Autowired
    FwGroupUserRepositoty fwGroupUserRepositoty;
    @Autowired
    UserRepository userRepository;
    @Autowired
    TaskFromService taskFromService;

    @Value("${role.dataCollectCode}")
    private String dataCollectCode;

    @Value("${role.puCollectCode}")
    private String puCollectCode;
    @Value("${role.xcCollectCode}")
    private String xcCollectCode;

    @Override
    public void saveGroup(HttpServletRequest request, FwGroupEntityVo fwGroupEntityVo, String type) {
        String uuid = UUIDGenerator.getUUID();
        FwGroupEntity fwGroupEntity = new FwGroupEntity();
        fwGroupEntity.setId(uuid);
        fwGroupEntity.setDelFlag(Constant.IS_VALID_YES);
        fwGroupEntity.setDivision(fwGroupEntityVo.getDivision());
        fwGroupEntity.setGroupLeader(fwGroupEntityVo.getGroupLeader());
        fwGroupEntity.setGroupLeaderId(fwGroupEntityVo.getGroupLeaderId());
        String fullName = fwDivisionService.findFullNameById(fwGroupEntityVo.getDivision());
        fwGroupEntity.setAddress(fullName);
        fwGroupEntity.setGroupType(fwGroupEntityVo.getGroupType());
        fwGroupEntity.setGroupMember(fwGroupEntityVo.getGroupMember());
        fwGroupEntity.setGroupName(fwGroupEntityVo.getGroupName());
        fwGroupEntity.setDivisionName(fwGroupEntityVo.getDivisionName());
        fwGroupEntity.setCreateTime(new Date());
        fwGroupRepository.save(fwGroupEntity);
        if (Constant.USER_TYPE_PC.equals(type)) {
            RoleUserEntity roleUserEntity = new RoleUserEntity();
            RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(dataCollectCode);
            roleUserEntity.setRoleId(roleByCode.getRoleId());
            roleUserEntity.setUserId(fwGroupEntityVo.getGroupLeaderId());
            if (!StringUtils.isEmpty(roleByCode)) {
                PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
            }
        }
        if (Constant.USER_TYPE_XC.equals(type)) {
            RoleUserEntity roleUserEntity = new RoleUserEntity();
            RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(dataCollectCode);
            roleUserEntity.setRoleId(roleByCode.getRoleId());
            roleUserEntity.setUserId(fwGroupEntityVo.getGroupLeaderId());
            if (!StringUtils.isEmpty(roleByCode)) {
                PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
            }
        }
        String ids = fwGroupEntityVo.getGroupUserId();
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        List<FwGroupUserEntity> list = new ArrayList<>();
        if (!StringUtils.isEmpty(idList) && idList.size() > 0) {
            for (String id : idList) {
                FwGroupUserEntity fwGroupUserEntity = new FwGroupUserEntity();
                fwGroupUserEntity.setId(UUIDGenerator.getUUID());
                fwGroupUserEntity.setGroupId(uuid);
                fwGroupUserEntity.setUserId(id);
                fwGroupUserEntity.setCreatTime(new Date());
                list.add(fwGroupUserEntity);
                if (Constant.USER_TYPE_PC.equals(type)) {
                    RoleUserEntity roleUserEntity = new RoleUserEntity();
                    RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(puCollectCode);
                    roleUserEntity.setRoleId(roleByCode.getRoleId());
                    roleUserEntity.setUserId(id);
                    if (!StringUtils.isEmpty(roleByCode)) {
                        PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                    }
                }
                if (Constant.USER_TYPE_XC.equals(type)) {
                    RoleUserEntity roleUserEntity = new RoleUserEntity();
                    RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(xcCollectCode);
                    roleUserEntity.setRoleId(roleByCode.getRoleId());
                    roleUserEntity.setUserId(id);
                    if (!StringUtils.isEmpty(roleByCode)) {
                        PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                    }
                }
            }
        }
        fwGroupUserService.saveGroupIdAndUserId(list);
    }

    /***
     * 查询分组
     * @param request
     * @param fwGroupVo
     * @param curPage
     * @param pageSize
     * @return
     */

    @Override
    public JSONObject getPage(HttpServletRequest request, FwGroupVo fwGroupVo, int curPage, int pageSize,String groupType) {
        Page<FwGroupEntity> page = fwGroupQueryRepository.getPage(request, fwGroupVo, curPage, pageSize,groupType);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    @Transactional
    @Override
    public void deletGroup(List<String> ids) {
        Date updateTime = new Date();
        fwGroupRepository.deletGroup(ids, updateTime);
        for (String id : ids) {
            List<FwGroupUserEntity> byGroupId = fwGroupUserService.findByGroupId(id);
            if (!StringUtils.isEmpty(byGroupId)) {
                fwGroupUserService.deletGroupIdAndUserId(byGroupId);
            }
        }
    }

    @Override
    public List<FwGroupEntity> findListById(List<String> ids) {
        List<FwGroupEntity> allById = fwGroupRepository.findAllById(ids);
        return allById;
    }

    @Override
    @Transactional
    public void updateGroup(FwGroupEntityVo fwGroupEntityVo, String type) {
        FwGroupEntity fwGroup = fwGroupRepository.findById(fwGroupEntityVo.getId()).get();
        FwGroupEntity fwGroupEntity = new FwGroupEntity();
        fwGroupEntity.setId(fwGroupEntityVo.getId());
        fwGroupEntity.setGroupLeader(fwGroupEntityVo.getGroupLeader());
        fwGroupEntity.setGroupName(fwGroupEntityVo.getGroupName());
        fwGroupEntity.setGroupMember(fwGroupEntityVo.getGroupMember());
        String fullName = fwDivisionService.findFullNameById(fwGroupEntityVo.getDivision());
        fwGroupEntity.setAddress(fullName);
        fwGroupEntity.setDelFlag(Constant.IS_VALID_YES);
        fwGroupEntity.setCreateTime(fwGroup.getCreateTime());
        fwGroupEntity.setUpdateTime(new Date());
        fwGroupEntity.setDivision(fwGroupEntityVo.getDivision());
        fwGroupEntity.setGroupNum(fwGroupEntityVo.getGroupNum());
        fwGroupEntity.setDivisionName(fwGroupEntityVo.getDivisionName());
        fwGroupEntity.setGroupLeaderId(fwGroupEntityVo.getGroupLeaderId());
        fwGroupEntity.setGroupType(fwGroupEntityVo.getGroupType());
        fwGroupRepository.save(fwGroupEntity);
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(fwGroupEntityVo.getGroupLeaderId());
        boolean isExist = isHave(roles);
        if (isExist) {
            if (Constant.USER_TYPE_PC.equals(type)) {
                RoleUserEntity roleUserEntity = new RoleUserEntity();
                RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(dataCollectCode);
                roleUserEntity.setRoleId(roleByCode.getRoleId());
                roleUserEntity.setUserId(fwGroupEntityVo.getGroupLeaderId());
                if (!StringUtils.isEmpty(roleByCode)) {
                    PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                }
            }
            if (Constant.USER_TYPE_XC.equals(type)) {
                RoleUserEntity roleUserEntity = new RoleUserEntity();
                RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(dataCollectCode);
                roleUserEntity.setRoleId(roleByCode.getRoleId());
                roleUserEntity.setUserId(fwGroupEntityVo.getGroupLeaderId());
                if (!StringUtils.isEmpty(roleByCode)) {
                    PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                }
            }
        }
        List<FwGroupUserEntity> allByGroupId = fwGroupUserService.findByGroupId(fwGroupEntityVo.getId());
        fwGroupUserService.deletGroupIdAndUserId(allByGroupId);
        String ids = fwGroupEntityVo.getGroupUserId();
        if (!StringUtils.isEmpty(ids)) {
            String[] split = ids.split(",");
            List<String> idList = Arrays.asList(split);
            List<FwGroupUserEntity> list = new ArrayList<>();
            for (String id : idList) {
                List<RoleEntity> role = PlatformAPI.getOrgAPI().getUserAPI().getRoles(id);
                boolean isExistUser = isHave(role);
                if (isExistUser) {
                    if (Constant.USER_TYPE_PC.equals(type)) {
                        RoleUserEntity roleUserEntity = new RoleUserEntity();
                        RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(puCollectCode);
                        roleUserEntity.setRoleId(roleByCode.getRoleId());
                        roleUserEntity.setUserId(id);
                        if (!StringUtils.isEmpty(roleByCode)) {
                            PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                        }
                    }
                    if (Constant.USER_TYPE_XC.equals(type)) {
                        RoleUserEntity roleUserEntity = new RoleUserEntity();
                        RoleEntity roleByCode = PlatformAPI.getOrgAPI().getRoleAPI().getRoleByCode(xcCollectCode);
                        roleUserEntity.setRoleId(roleByCode.getRoleId());
                        roleUserEntity.setUserId(id);
                        if (!StringUtils.isEmpty(roleByCode)) {
                            PlatformAPI.getOrgAPI().getRoleAPI().saveRoleUser(roleUserEntity);
                        }
                    }
                }
                FwGroupUserEntity fwGroupUserEntity = new FwGroupUserEntity();
                fwGroupUserEntity.setId(UUIDGenerator.getUUID());
                fwGroupUserEntity.setGroupId(fwGroupEntityVo.getId());
                fwGroupUserEntity.setUserId(id);
                fwGroupUserEntity.setCreatTime(new Date());
                list.add(fwGroupUserEntity);
            }
            fwGroupUserService.saveGroupIdAndUserId(list);
        }
    }

    @Override
    public GroupVo findById(String groupId) {
        GroupVo groupVo=new GroupVo();
        FwGroupEntity fwGroupEntity = fwGroupRepository.findById(groupId).get();
        groupVo.setFwGroupEntity(fwGroupEntity);
        List<FwGroupUserEntity> allByGroupId = fwGroupUserRepositoty.findAllByGroupId(groupId);
        List<UserEntity> userEntityList=new ArrayList<>();
        //TreeSet<UserEntity> userEntityList = new TreeSet<>();
        allByGroupId.forEach(fwGroupUserEntity -> {
            UserEntity oneByUserId = userRepository.findOneByUserId(fwGroupUserEntity.getUserId());
            if(oneByUserId==null){
                return;
            }
            userEntityList.add(oneByUserId);
        });
        //List<UserEntity> list=new ArrayList<UserEntity>(userEntityList);
        groupVo.setList(userEntityList);
        return groupVo;
    }

    @Override
    public List<FwGroupUserFormCountVO> findGroupUser(String groupId) {
        FwGroupEntity fwGroupEntity = fwGroupRepository.findById(groupId).get();
        List<FwGroupUserEntity> allByGroupId = fwGroupUserRepositoty.findAllByGroupId(groupId);
        List<FwGroupUserFormCountVO> list = new ArrayList<>();
        FwGroupUserFormCountVO userFormCountVO = new FwGroupUserFormCountVO();
        if (!StringUtils.isEmpty(fwGroupEntity)) {
            String leaderId = fwGroupEntity.getGroupLeaderId();
            UserEntity userEntity = userRepository.findById(leaderId).get();
            userFormCountVO.setIdNumber(userEntity.getIdCard());
            userFormCountVO.setMobilePhone(userEntity.getMobilePhone());
            userFormCountVO.setRelName(userEntity.getUserName());
            userFormCountVO.setUserId(leaderId);
            userFormCountVO.setGroupZW("组长");
            Long userIdCount = taskFromService.findByUserIdCount(leaderId);
            String count = String.valueOf(userIdCount);
            userFormCountVO.setFormNum(count);
            list.add(userFormCountVO);
        }
        if (list.size() > 0) {
            allByGroupId.forEach(fwGroupUserEntity -> {
                FwGroupUserFormCountVO userFormCount = new FwGroupUserFormCountVO();
                UserEntity userEntity = userRepository.findById(fwGroupUserEntity.getUserId()).get();
                userFormCount.setGroupZW("组员");
                userFormCount.setRelName(userEntity.getUserName());
                userFormCount.setMobilePhone(userEntity.getMobilePhone());
                userFormCount.setIdNumber(userEntity.getIdCard());
                String userId = fwGroupUserEntity.getUserId();
                Long userIdCount = taskFromService.findByUserIdCount(userId);
                String count = String.valueOf(userIdCount);
                userFormCount.setFormNum(count);
                userFormCount.setUserId(userId);
                list.add(userFormCount);
            });
        }
        return list;
    }

    @Override
    public List<FwGroupEntity> findByGroupLeaderId(String groupLeaderID) {
        List<FwGroupEntity> byGroupLeaderId = fwGroupRepository.findAllByGroupLeaderId(groupLeaderID);
        return byGroupLeaderId;
    }

    @Override
    public JSONObject getPageGroup(HttpServletRequest request, FwGroupVo fwGroupVo, int curPage, int pageSize) {
        Page<FwGroupEntity> page = fwGroupQueryRepository.getPageGroup(request, fwGroupVo, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(page);
        return jsonObject;
    }

    public boolean isHave(List<RoleEntity> list) {
        boolean flag=true;
        for (RoleEntity role : list) {
            if (dataCollectCode.equals(role.getRoleCode())) {
                flag=false;
                break;
            }
            if(xcCollectCode.equals(role.getRoleCode())){
                flag=false;
                break;
            }
            if(puCollectCode.equals(role.getRoleCode())){
                flag=false;
                break;
            }
        }
        if (!flag) {
            return false;
        }else {
            return true;
        }
    }
}
